﻿CREATE PROCEDURE [dbo].[sec__CheckTableAccess]
	@RowCount int,
	@ColsUpdated varbinary(1024),
	@ProcID int,
	@StatusID int,
	@AccessID int,
	@TablePK int = 0,
	@StatusIDPrev int = 0
AS

IF @ROWCOUNT = 0 RETURN
SET NOCOUNT ON

PRINT OBJECT_NAME(@@PROCID)+':@StatusID'+STR(@StatusID)
PRINT OBJECT_NAME(@@PROCID)+':@StatusIDPrev'+STR(ISNULL(@StatusIDPrev,-1))
PRINT OBJECT_NAME(@@PROCID)+':'+dbo.fn_ColumnsUpdated(@ColsUpdated,@PROCID)

DECLARE @TableName sysname SET @TableName = dbo.fs_TableName(OBJECT_NAME(@ProcID))

IF @TableName IS NULL BEGIN
	ROLLBACK
	DECLARE @CU sysname SET @CU	 = SYSTEM_USER
	RAISERROR('User %s does not have access to view definition of object %d.',16,1,@CU,@@PROCID)
	RETURN
END

IF dbo.fn_ColumnsUpdated(@ColsUpdated,@PROCID) = 'StatusID' RETURN

DECLARE @Cols nvarchar(4000) SET @Cols = dbo.fn_ColumnsUpdated(@ColsUpdated,@PROCID)

IF NOT OBJECT_ID('tempdb..#StatusIDs') IS NULL AND (@RowCount IS NULL OR @RowCount > 1 ) BEGIN
	SET @StatusID = NULL
	SELECT @StatusID = IDs.StatusID FROM #StatusIDs IDs OUTER APPLY fs_StateID(StatusID,@AccessID) fs WHERE fs.ID IS NULL
	IF @StatusID IS NULL RETURN
	IF dbo.Context_IsSecurityOff() > 0 RETURN
END
ELSE BEGIN
	IF @ROWCOUNT > 1 BEGIN ROLLBACK TRAN RAISERROR('Multi-row updates are not allowed for %s',16,1,@TableName) RETURN END
	IF ISNULL(@StatusID,0) = 0 BEGIN ROLLBACK TRAN RAISERROR('StatusID must not be greater then Zero:[%d]',16,1,@StatusID) RETURN END
	IF EXISTS(SELECT * FROM fs_StateID(@StatusID,@AccessID)) OR
		 EXISTS(SELECT * FROM fs_StateID(@StatusIDPrev,@AccessID)) RETURN
	IF dbo.Context_IsSecurityOff() > 0 RETURN
END

ROLLBACK TRAN

DECLARE @User sysname, @Group sysname,@Status sysname,@Access sysname, @Msg nvarchar(4000)
SELECT @User = dbo.UserName(),@Group = dbo.UserGroups_TEXT(), @Status = s.Name,@Access = a.Name,@Msg = dbo.Config_AccessDeniedMessage()+'
['+ISNULL(@Cols,'')+']'
FROM t_State s CROSS JOIN ts_StateAccess a WHERE s.ID = @StatusID AND a.ID = @AccessID

IF @TablePK > 0 SET @TableName = @TableName+ '(ID:'+CONVERT(varchar,@TablePK)+')'

RAISERROR(@Msg,16,1,@User,@Group,@Access,@TableName,@Status)





